#!/bin/bash
# REQUEST_FOR_LOG_TYPE_ARRAY=("Notification" "Pgyer")
# sh ${CommonFun_HomeDir_Absolute}/brances_info/brances_info_log/brances_info_log.sh -envInfoF "${Package_Environment_FILE_PATH}" --request-for-log-types "${REQUEST_FOR_LOG_TYPE_ARRAY[*]}" -comScriptHomeDir "${CommonFun_HomeDir_Absolute}" -resultSaveToJsonF "${TEST_DATA_RESULT_FILE_PATH}"
JQ_EXEC=`which jq`


exit_script() { # 退出脚本的方法，省去当某个步骤失败后，还去继续多余的执行其他操作
    exit 1
}


# 定义颜色常量
NC='\033[0m' # No Color
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'


# 当前【shell脚本】的工作目录
# $PWD代表获取当前路径，当cd后，$PWD也会跟着更新到新的cd路径。这个和在终端操作是一样的道理的
CurrentDIR_Script_Absolute="$( cd "$( dirname "$0" )" && pwd )"
#echo "CurrentDIR_Script_Absolute=${CurrentDIR_Script_Absolute}"
#CommonFun_HomeDir_Absolute2=${CurrentDIR_Script_Absolute}/..
CommonFun_HomeDir_Absolute2=${CurrentDIR_Script_Absolute%/*}
CommonFun_HomeDir_Absolute=${CommonFun_HomeDir_Absolute2%/*}

qscript_path_get_filepath="${CommonFun_HomeDir_Absolute}/qscript_path_get.sh"
qbase_function_log_msg_script_path="$(sh ${qscript_path_get_filepath} qbase function_log_msg)"
source $qbase_function_log_msg_script_path # 为了使用 logResultValueToJsonFile 、 logResultValueToJsonFile
echo "${YELLOW}引入文件： ${BLUE}${qbase_function_log_msg_script_path}${NC}"

qbase_update_json_file_singleString_script_path="$(sh ${qscript_path_get_filepath} qbase update_json_file_singleString)"
qbase_json_file_check_script_path="$(sh ${qscript_path_get_filepath} qbase json_file_check)"



get_current_branch_log_script_path="${CommonFun_HomeDir_Absolute}/brances_info/brances_info_log/get_current_branch_log.sh"
get_lastest_branch_log_script_path="${CommonFun_HomeDir_Absolute}/brances_info/brances_info_log/get_lastest_branch_log.sh"








function logSuccessMsg() {
    printf "${GREEN}$1${GREEN}\n${NC}"
}

function logMsg() {
    printf "$1\n${NC}"
}

function debug_log() {
    if [ "${isRelease}" == true ]; then
        echo "$1"
    fi
}


# shell 参数具名化
show_usage="args: [-envInfoF, -requestFors, -comScriptHomeDir, -resultSaveToJsonF]\
                                  [---environment-json-file=, -request-for-log-types=, --common-script-home-dir=, --result-save-to-json-file-path=]"

while [ -n "$1" ]
do
        case "$1" in
                -envInfoF|--environment-json-file) Environment_FILE_PATH=$2; shift 2;; # 环境文件
                -requestFors|--request-for-log-types) REQUEST_FOR_LOG_TYPE_ARRAY_STRING=$2; shift 2;;   # 要请求哪些类型 ("Notification" "Pgyer")
                -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
                --) break ;;
                *) echo $1,$2,$show_usage; break ;;
        esac
done
# 参数1：
if [ ! -f "${Environment_FILE_PATH}" ]; then
    echo "❌:您的环境文件Environment_FILE_PATH=${Environment_FILE_PATH}未设置或不存在，请先设置"
    exit_script
fi

# 参数4
if [ ! -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ]; then
    echo "❌:您通过 -resultSaveToJsonF 传入的要存放分支信息文件路径RESULT_SALE_TO_JSON_FILE_PATH=${RESULT_SALE_TO_JSON_FILE_PATH}还未设置或者不存在，请检查！"
    exit_script
fi




# 初始化最后的分支信息，并保存到环境文件中指定的那个保存文件里，方便后续直接从文件中获取
function initLastAllChangeLog() {
    while [ -n "$1" ]
    do
        case "$1" in
            -envInfoF|--environment-json-file) Environment_FILE_PATH=$2; shift 2;;
            # -developBranchsJsonF|--develop-branchs-json-file) Develop_Branchs_FILE_PATH=$2; shift 2;;
            # -historyVersionJsonF|--history-version-json-file) History_Versions_FILE_PATH=$2; shift 2;;
            -branchT|--branch-logType) branchLogType=$2; shift 2;;  # None \ Notification \ Pgyer
            -resultSaveToJsonF|--result-save-to-json-file-path) RESULT_SALE_TO_JSON_FILE_PATH=$2; shift 2;; # 为简化换行符的保真(而不是显示成换行,导致后面计算数组个数麻烦),将结果保存在的JSON文件
            --) break ;;
            *) echo $1,$2; break ;;
        esac
    done

    if [ ! -f "${Environment_FILE_PATH}" ]; then
        echo "❌Error: $FUNCNAME:您的环境文件${Environment_FILE_PATH}中未设置或不存在，请先检查设置"
        return 1
    fi
    
    if [ ! -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ]; then
        echo "❌Error: $FUNCNAME:您的环境文件${Environment_FILE_PATH}中未设置分支信息要存放的路径branchsResultJsonFile，请先设置"
        return 1
    fi
    sh ${qbase_update_json_file_singleString_script_path} -jsonF "${Environment_FILE_PATH}" -k "branchsResultJsonFile" -v "${RESULT_SALE_TO_JSON_FILE_PATH}"
    if [ $? != 0 ]; then
        echo "❌Error:设置等下用来保存结果的 branchsResultJsonFile 文件[${RESULT_SALE_TO_JSON_FILE_PATH}]未设置成功，请检查"
        return 1
    fi

    # 是 通知，且允许 markdown 的时候才能真正去尝试markdown
    NotificationMESSAGETYPE=$(cat $Environment_FILE_PATH | jq -r '.package_noti_msgtype')
    if [ "${branchLogType}" == "Notification" ] && [ "${NotificationMESSAGETYPE}" == "markdown" ]; then
        shouldMarkdownOther="true"
    else
        shouldMarkdownOther="false" # 之前未初始化，所以这里得赋值，避免Pgyer用了Notification的值
    fi

    FullChangeLogResult=''
    Escape_FULLTESTINFO_ARRAY_STRING=''
    
    CommitChangeLog=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} -r '.package_update_des') # -r 去除字符串引号
    if [ "${shouldMarkdownOther}" == "true" ]; then
        CommitChangeLog="<font color=warning>${CommitChangeLog}</font>"
    fi
    FullChangeLogResult+="${CommitChangeLog}"
    Escape_FULLTESTINFO_ARRAY_STRING+="\"${CommitChangeLog}\","
    
    if [ "${branchLogType}" == "none" ]; then
        echo "不需要其他打包的分支信息"
        return 0
    fi
    
#    echo "\n\n\n\n\n\n"
    echo "===========================获取当前打包信息(从 ${Environment_FILE_PATH} 的 .developBranchsJsonFile 指向的文件中)==========================="
    shouldMarkdownCurrent=${shouldMarkdownOther}
    Develop_Branchs_FILE_PATH=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} '.developBranchsJsonFile' | sed 's/\"//g')
    PackageNetworkType=$(cat $Environment_FILE_PATH | ${JQ_EXEC} .package_default_env | sed 's/\"//g')
    debug_log "${YELLOW}正在调用方法(获取当前打包信息,从 ${Develop_Branchs_FILE_PATH} 中):《 ${BLUE}sh $get_current_branch_log_script_path -devBranchsJsonF \"${Develop_Branchs_FILE_PATH}\" -branchLogFor \"${branchLogType}\" -pn \"${PackageNetworkType}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" ${YELLOW}》${NC}"
    sh $get_current_branch_log_script_path -devBranchsJsonF "${Develop_Branchs_FILE_PATH}" -branchLogFor "${branchLogType}" -pn "${PackageNetworkType}" -shouldMD "${shouldMarkdownCurrent}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}"
    if [ $? != 0 ]; then
        echo "❌Error: 在$FUNCNAME里执行 getCurrentBranchLog 失败，请先检查"
        return 1
    fi


    Escape_CURRENT_ARRAY_STRING=$(cat "${RESULT_SALE_TO_JSON_FILE_PATH}" | jq ".branch_info_result.${branchLogType}.current.full_slice")
    # logResultObjectStringToJsonFile "${Escape_CURRENT_ARRAY_STRING}"
    if [ -n "${Escape_CURRENT_ARRAY_STRING}" ]; then
        Escape_CURRENT_ARRAY_STRING=${Escape_CURRENT_ARRAY_STRING: 1:${#Escape_CURRENT_ARRAY_STRING}-2} # 去除头尾的[]，共两个字符
    fi
    # logResultObjectStringToJsonFile "[${Escape_CURRENT_ARRAY_STRING}]"
    Escape_FULLTESTINFO_ARRAY_STRING+="${Escape_CURRENT_ARRAY_STRING}," # 注意📢:这里不用重复前后多加引号了
    # logResultObjectStringToJsonFile "[${Escape_FULLTESTINFO_ARRAY_STRING}]"


    # #echo "获取到的当前打包信息=============${currentBranchLogStringResult}"
    # if [ -n "${currentBranchLogStringResult}" ] ; then
    #     if [ "${shouldMarkdownOther}" == "true" ]; then
    #         FullChangeLogResult+="\n\n\n" # 用企业微信发送 markdown 内容时候，居然三个\n才有空一行纯空的
    #         Escape_FULLTESTINFO_ARRAY_STRING+="\"\","
    #         Escape_FULLTESTINFO_ARRAY_STRING+="\"\","
    #     else
    #         FullChangeLogResult+="\n\n"
    #         Escape_FULLTESTINFO_ARRAY_STRING+="\"\","
    #     fi
    #     FullChangeLogResult+="${currentBranchLogStringResult}"

    #     Escape_FULLTESTINFO_ARRAY_STRING+="${Escape_CURRENT_ARRAY_STRING}," # 注意📢:这里不用重复前后多加引号了
    # fi
    
    

#    echo "\n\n\n\n\n\n"
    echo "===========================获取上个线上版本分支信息(从 ${Environment_FILE_PATH} 的 .historyVersionJsonFile 指向的文件中)==========================="
    shouldMarkdownLastOnline="false"
    History_Versions_FILE_PATH=$(cat ${Environment_FILE_PATH} | ${JQ_EXEC} '.historyVersionJsonFile' | sed 's/\"//g')
    debug_log "${YELLOW}正在调用方法(获取上个线上版本分支信息,从 ${History_Versions_FILE_PATH} 中):《 ${BLUE}sh $get_lastest_branch_log_script_path -historyVersionJsonF \"${History_Versions_FILE_PATH}\" -branchLogFor \"${branchLogType}\" -pn \"${PackageNetworkType}\" -resultSaveToJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" ${YELLOW}》${NC}"
    sh $get_lastest_branch_log_script_path -historyVersionJsonF "${History_Versions_FILE_PATH}" -branchLogFor "${branchLogType}" -pn "${PackageNetworkType}" -resultSaveToJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}"
    if [ $? != 0 ]; then
        echo "❌Error: 在 $FUNCNAME 里执行 getLastOnlineVersionLog 失败，请先检查"
        return 1
    fi
    #echo "获取到的上个线上版本分支信息============="
    # Escape_FULLTESTINFO_ARRAY_STRING+="上个线上版本分支信息：,"


    Escape_LASTONLINE_ARRAY_STRING=$(cat "${RESULT_SALE_TO_JSON_FILE_PATH}" | jq ".branch_info_result.${branchLogType}.lastOnline.full_slice")
    # logResultObjectStringToJsonFile "${Escape_LASTONLINE_ARRAY_STRING}"
    if [ -n "${Escape_LASTONLINE_ARRAY_STRING}" ]; then
        Escape_LASTONLINE_ARRAY_STRING=${Escape_LASTONLINE_ARRAY_STRING: 1:${#Escape_LASTONLINE_ARRAY_STRING}-2} # 去除头尾的[]，共两个字符
    fi
    # logResultObjectStringToJsonFile "[${Escape_LASTONLINE_ARRAY_STRING}]"
    Escape_FULLTESTINFO_ARRAY_STRING+="${Escape_LASTONLINE_ARRAY_STRING}," # 注意📢:这里不用重复前后多加引号了
    # logResultObjectStringToJsonFile "[${Escape_FULLTESTINFO_ARRAY_STRING}]"

    # if [ -n "${lastOnlineVersionLogStringResult}" ] ; then
    #     # 注意📢：由于 markdown_quote 是使用 echo 来返回值的，所以会丢失其中的换行符，所以我们在修复前，不使用该方法，而直接写源码
    #     # lastOnlineVersionLogStringResult=$(markdown_quote "${shouldMarkdownOther}" "${lastOnlineVersionLogStringResult}")
    #    Escape_LASTONLINE_ARRAY_STRING_noQuote=${Escape_LASTONLINE_ARRAY_STRING: 1:${#Escape_LASTONLINE_ARRAY_STRING}-2} # 去除前后的双引号,才能方便修改
    #    if [ "${shouldMarkdownOther}" == "true" ]; then
    #         lastOnlineVersionLogStringResult=">${lastOnlineVersionLogStringResult}"
    #         FullChangeLogResult+="\n\n" # 用企业微信发送 markdown 内容时候，居然三个\n才有空一行纯空的
    #         # 旧版本使用markdown的引用来更加区分它,且不加尾部不加逗号，因为不用换行
    #         Escape_FULLTESTINFO_ARRAY_STRING+="\">${Escape_LASTONLINE_ARRAY_STRING_noQuote}\","
    #     else
    #         FullChangeLogResult+="\n\n"
    #         # Escape_FULLTESTINFO_ARRAY_STRING+="\"\","   # 用,来换行
    #         Escape_FULLTESTINFO_ARRAY_STRING+="\"\n${Escape_LASTONLINE_ARRAY_STRING_noQuote}\","
    #     fi
    #     FullChangeLogResult+="${lastOnlineVersionLogStringResult}"
    # fi

    
    # 更新
    # FullChangeLogResult="111\n222" # 测试下面更新代码时候使用的简易值
    RESULT_ALL_STRING_SALE_BY_KEY="branch_info_result.${branchLogType}.all.text"
    if [ -f "${RESULT_SALE_TO_JSON_FILE_PATH}" ] && [ -n "${RESULT_ALL_STRING_SALE_BY_KEY}" ]; then
        sh ${CommonFun_HomeDir_Absolute}/update_json_file.sh -f "${RESULT_SALE_TO_JSON_FILE_PATH}" -sk "${RESULT_ALL_STRING_SALE_BY_KEY}" -sv "\"${FullChangeLogResult}\"" --skip-value-check "true"
        if [ $?  != 0 ]; then 
            echo "❌更新最后获得的所有分支信息字符串到文件中，错误啦1。。。。。。"
            exit 1
        fi

        # 去除最后一个字符,即逗号","
        if [ -n "${Escape_FULLTESTINFO_ARRAY_STRING}" ] && [ "${Escape_FULLTESTINFO_ARRAY_STRING}" != "[" ]; then
            Escape_FULLTESTINFO_ARRAY_STRING=${Escape_FULLTESTINFO_ARRAY_STRING: 0:${#Escape_FULLTESTINFO_ARRAY_STRING}-1}
        fi
        all_slice_key="branch_info_result.${branchLogType}.all.slice"
        sh ${CommonFun_HomeDir_Absolute}/update_json_file.sh -f "${RESULT_SALE_TO_JSON_FILE_PATH}" -sk "${all_slice_key}" -sv "[${Escape_FULLTESTINFO_ARRAY_STRING}]" --skip-value-check "true"
        if [ $?  != 0 ]; then 
            echo "$FUNCNAME ❌更新最后获得的所有分支信息字符串到文件中，错误啦3。。。。。。"
            exit 1
        fi
    fi


    # 因为替换的内容比较多，为避免之后使用问题，提前检查替换后是否还是个标准的json文件，防止后续解析失败
    debug_log "正在执行命令(检查分支信息文件的JSON有效性:避免一堆对json的操作后,导致格式不规范,从而影响该文件后续的解析使用)：《 sh ${qbase_json_file_check_script_path} -checkedJsonF \"${RESULT_SALE_TO_JSON_FILE_PATH}\" -scriptResultJsonF \"${SCRIPT_RESULT_JSON_FILE}\" 》"
    sh ${qbase_json_file_check_script_path} -checkedJsonF "${RESULT_SALE_TO_JSON_FILE_PATH}" -scriptResultJsonF "${SCRIPT_RESULT_JSON_FILE}"
    if [ $? != 0 ]; then
        exit_script
    fi
}



REQUEST_FOR_LOG_TYPE_ARRAY=($REQUEST_FOR_LOG_TYPE_ARRAY_STRING)
REQUEST_FOR_LOG_TYPE_COUNT=${#REQUEST_FOR_LOG_TYPE_ARRAY[*]}
echo "要请求的信息类型有${REQUEST_FOR_LOG_TYPE_COUNT}个，分别为REQUEST_FOR_LOG_TYPE_ARRAY=${REQUEST_FOR_LOG_TYPE_ARRAY[*]}"
# 1、先检查文件，避免执行了N个后，才再最后发现有文件缺失，导致整个获取过程以失败告终

# 2、文件检查通过后，正式获取信息
for((i=0;i<${REQUEST_FOR_LOG_TYPE_COUNT};i++));
do
    REQUEST_FOR_LOG_TYPE_STRING=${REQUEST_FOR_LOG_TYPE_ARRAY[i]}
    echo "${YELLOW}正在执行$((i+1))/$((REQUEST_FOR_LOG_TYPE_COUNT))命令以获取分支信息给 ${BLUE}${REQUEST_FOR_LOG_TYPE_STRING}${NC} ${YELLOW}使用：《 ${BLUE}initLastAllChangeLog -envInfoF \"${Environment_FILE_PATH}\" --branch-logType \"${REQUEST_FOR_LOG_TYPE_STRING}\" ${YELLOW}》${NC}"
    initLastAllChangeLog -envInfoF "${Environment_FILE_PATH}" --branch-logType "${REQUEST_FOR_LOG_TYPE_STRING}"
    if [ $? != 0 ]; then
        exit_script
    fi
done
